<template>
  <el-card shadow="never">
    <el-button @click="addUI" class="left">添加</el-button>
    <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        height="480"
        row-key="permissionId"
        border
    >
      <el-table-column prop="roleId" label="角色id" sortable>
      </el-table-column>
      <el-table-column prop="roleName" label="角色名称" sortable>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="danger" plain @click="del(scope.row)">删除</el-button>
          <el-button type="info" plain @click="updateUI(scope.row)">修改</el-button>
          <el-button type="info" plain @click="distributePermissionToRole(scope.row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="角色" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-input v-model="form.roleName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdate()"
        >确 定
        </el-button
        >
      </div>
    </el-dialog>
  </el-card>
</template>

<script>

import {findAll, doSaveOrUpdate, deleteByroleId} from '@/api/role/index.js'

export default {
  data() {
    return {
      tableData: [],
      form: {},
      dialogFormVisible: false,
      formLabelWidth: "180px"
    }
  },
  mounted() {
    this.updateTable();
  },
  methods: {
    updateTable() {
      findAll().then(r => {
        this.tableData = r.data;
      })
    },
    addUI() {
      this.dialogFormVisible = true;
      this.form = {};
    },
    del(row) {
      this.$confirm("确认删除?")
          .then(() => {
            let roleId = row.roleId;
            deleteByroleId(roleId).then(r => {
              if (r.code == 200) {
                this.updateTable();
                this.$message.success("删除成功");
                return;
              }
              this.$message.error("删除失败");
            })
          })
          .catch(() => {

          })
    },
    updateUI(row) {
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogFormVisible = true;
    },
    saveOrUpdate() {
      doSaveOrUpdate(this.form).then(r => {
        if (r.code == 200) {
          this.dialogFormVisible = false;
          this.updateTable();
        }
      })
    },
    distributePermissionToRole(row) {
      this.$router.push(`/DistributePermissionToRole/${row.roleId}`);
    }
  }
}
</script>

<style lang="less" scoped>
.left {
  margin: 10px 0;
}
</style>